<!-- eslint-disable no-console -->
<script lang="ts" setup>
import type { QcdefectApi } from '#/api';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { addQcdefect, updateQcdefect } from '#/api';

const emit = defineEmits(['success']);

const formdata = ref<QcdefectApi.Row>();
const mes_index_type = ref();
const mes_defect_level = ref();

const [Modal, modalApi] = useVbenModal({
  closeOnClickModal: false,
  async onConfirm() {
    const { valid } = await baseFormApi.validate();
    if (valid) {
      modalApi.lock();

      let data;
      await baseFormApi.getValues().then((res) => {
        console.log(res);
        data = res;
      });
      try {
        await (formdata.value?.defectId
          ? updateQcdefect(data!)
          : addQcdefect(data!));
        modalApi.close();
        emit('success');
      } finally {
        modalApi.lock(false);
      }
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData();
      if (data) {
        formdata.value = data.row;
        console.log(formdata.value);
        baseFormApi.setValues(formdata.value as any);
        mes_index_type.value = data.mes_index_type;
        mes_defect_level.value = data.mes_defect_level;
      }
    }
  },
});

const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  // 提交函数
  handleSubmit: onSubmit,

  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      rules: 'required',
      dependencies: {
        show: false,
        triggerFields: ['defectId'],
      },
      fieldName: 'defectId',
      label: 'Id',
    },
    {
      component: 'Textarea',
      rules: 'required',
      componentProps: {
        placeholder: '请输入缺陷描述',
      },
      fieldName: 'defectName',
      label: '缺陷描述',
    },
    {
      component: 'Select',
      rules: 'required',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: mes_index_type,
        placeholder: '请选择',
        showSearch: true,
      },
      fieldName: 'indexType',
      label: '检测项类型',
    },
    {
      component: 'Select',
      rules: 'required',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: mes_defect_level,
        placeholder: '请选择',
        showSearch: true,
      },
      fieldName: 'defectLevel',
      label: '缺陷等级',
    },
  ],
  wrapperClass: 'grid-cols-1',
});

function onSubmit(values: Record<string, any>) {
  console.log(values);

  modalApi.close();
}
</script>
<template>
  <Modal> <BaseForm /></Modal>
</template>
